param
	(	[system.IO.DirectoryInfo]$DeploymentPackageFolder
	,	[string]$DeploymentPackageDest
	,	[string]$targetenv
	,	[switch]$zip
	,	[switch]$emailnotification
	,	[switch]$notifications
	,	[switch]$biztalkprimary
	)
. "..\Deploy\Install\_Init.ps1"

#Determine the Latest build
function Expand-BuildNumber ($name)
{
	if ($name -match "^(?'1'\d*)\.(?'2'\d*)\.(?'3'\d*)\.(?'4'\d*)$")
	{ 
		'{0:D5}.{1:D5}.{2:D5}.{3:D5}' -f [int]$matches[1],[int]$matches[2],[int]$matches[3],[int]$matches[4]
	}
	else
	{
		''
	}
}

# ---------------------------------------------------------------------------
function Get-MaxBuildNumber($DeploymentPackageFolder)
{
	dir $DeploymentPackageFolder.fullname `
	| select Name,@{Name='Expanded'; Expression={Expand-BuildNumber $_.Name}} `
	| sort -Property Expanded -des `
	| select -First 1 `
	| foreach{[string]$_.Name}
}
 
$Build = Get-MaxBuildNumber $DeploymentPackageFolder

if ([system.String]::IsNullOrEmpty($Build))
{
  Write-Warning "No Build package was found. Nothing to deploy."
  exit
}
[system.IO.DirectoryInfo]$DeploymentPackageParentPath = ($DeploymentPackageFolder.Parent).FullName
$DeployProgressFile = [system.IO.Path]::Combine($DeploymentPackageParentPath,'DepoymentInProgress.txt')
if (Test-Path $DeployProgressFile)
{
	Write-Warning "A deployment is in progress. Script Halted." -ForegroundColor Yellow
	exit
}

##############################################################################

# Create the deployment in progress file
$null = New-Item -path $DeploymentPackageParentPath -Name DepoymentInProgress.txt -ItemType "file"

# execute deploy
Write-Host "Before - do we have any errors " $Error.Count
[system.IO.DirectoryInfo]$DeploymentPackageBuild = [system.IO.Path]::Combine($DeploymentPackageFolder.fullname,$Build)

function Execute-Deploy($DeploymentPackageFolder,$Build,$targetenv)
{
	$powershellcmdstring = ".\deploy.ps1 -targetenv $targetenv -noprompt -execute"
	if ($emailnotification)
	{
  	$powershellcmdstring +=  " -emailnotification"
  }
	elseif ($notifications)
	{
    $powershellcmdstring += " -notifications"
	}
	if ($BiztalkPrimary)
	{
	  $powershellcmdstring += " -BizTalkPrimary"
	}
  push-location $DeploymentPackageBuild
	#grab project dashboard info
	[xml]$Deploymentinfo = get-content ./Install/CommonProductParameters.xml
	$Script:productname = $Deploymentinfo.variables.ProjectDashboardProductName
	$deployoutput = POWERSHELL -noprofile -noninteractive -command $powershellcmdstring
  $deployoutput | ForEach-Object {Write-Host $_}
  Remove-Item -path $DeployProgressFile -Force
	Write-Host "Error count is " $Error.Count
  if ($deployoutput -match "Error while executing Deployment")
  {
   Write-Error "Deployment Failed"
  }
  pop-location
}

Execute-Deploy $DeploymentPackageFolder $Build $targetenv

#Write-Host "Error count is " $Error.Count

if ($Error.Count -gt 0)
{
  Throw "Deployment Failed"
}
if ($Error.Count -lt 1)
{
  #After a successfull deployment send to destination folder
  if (-not(Test-Path $DeploymentPackageDest))
  {
		$null = New-Item -Path $DeploymentPackageDest -ItemType "directory"
  }

  Copy-item -path $DeploymentPackageBuild -destination $DeploymentPackageDest -Force -Recurse
	Write-Host "$DeploymentPackageBuild  was copied to  $DeploymentPackageDest"
	Remove-Item -Path $DeploymentPackageBuild -Force -Recurse

}

#cleanup - remove any build palckages not deployed
dir $DeploymentPackageFolder | ?{$_.Name -match "^(?'1'\d*)\.(?'2'\d*)\.(?'3'\d*)\.(?'4'\d*)$"} | remove-item -Force -recurse


